package com.dapeng.cleardatabackend.config;

import com.dapeng.cleardatabackend.common.ErrorCode;
import com.dapeng.cleardatabackend.exception.BusinessException;
import com.dapeng.cleardatabackend.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

/**
 * @author dapeng
 * @description 将字符串转换为枚举
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public @NonNull <T extends BaseEnum> Converter<String, T> getConverter(@NonNull Class<T> targetEnum) {
        return source -> {
            for (T enumConstant : targetEnum.getEnumConstants()) {
                if (enumConstant.getCode().equals(Integer.valueOf(source))) {
                    return enumConstant;
                }
            }
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "非法的枚举值:" + source);
        };
    }
}